package cn.iocoder.yudao.module.system.service.roledevice;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.system.controller.admin.roledevice.vo.RoleDevicePageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.roledevice.vo.RoleDeviceRespVO;
import cn.iocoder.yudao.module.system.controller.admin.roledevice.vo.RoleDeviceSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.roledevice.RoleDeviceDO;
import cn.iocoder.yudao.module.system.dal.mysql.roledevice.RoleDeviceMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.ROLE_DEVICE_NOT_EXISTS;

/**
 * 设备和角色关联 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class RoleDeviceServiceImpl implements RoleDeviceService {

    @Resource
    private RoleDeviceMapper roleDeviceMapper;

    @Override
    public Long createRoleDevice(List<RoleDeviceSaveReqVO> createReqVO) {
        for (RoleDeviceSaveReqVO roleDeviceSaveReqVO : createReqVO) {
            RoleDeviceDO roleDevice = BeanUtils.toBean(roleDeviceSaveReqVO, RoleDeviceDO.class);
            roleDevice.setDeleted(false);
            roleDeviceMapper.insert(roleDevice);
        }
        // 返回
        return 1L;
    }

    @Override
    public void updateRoleDevice(RoleDeviceSaveReqVO updateReqVO) {
        // 校验存在
        validateRoleDeviceExists(updateReqVO.getId());
        // 更新
        RoleDeviceDO updateObj = BeanUtils.toBean(updateReqVO, RoleDeviceDO.class);
        roleDeviceMapper.updateById(updateObj);
    }

    @Override
    public void deleteRoleDevice(RoleDeviceRespVO deleteReqVO) {
        Long id = deleteReqVO.getId();
        Long roleId = deleteReqVO.getRoleId();
        Long deviceId = deleteReqVO.getDeviceId();
        // 构建查询条件
        QueryWrapper<RoleDeviceDO> wrapper = new QueryWrapper<>();
        // 所有字段只要有值，就加入删除条件
        if (id != null) {
            wrapper.eq("id", id);
        }
        if (roleId != null) {
            wrapper.eq("role_id", roleId);
        }
        if (deviceId != null) {
            wrapper.eq("device_id", deviceId);
        }
        // 安全校验：防止无条件删除（全表删除）
        if (wrapper.isEmptyOfWhere()) {
            throw new IllegalArgumentException("删除条件不能为空，请提供 id、roleId 或 deviceId 至少一个");
        }
        // 可选：校验数据是否存在
        if (roleDeviceMapper.selectCount(wrapper) == 0) {
            throw new RuntimeException("未找到匹配的记录，无法删除");
        }
        // 执行删除
        roleDeviceMapper.delete(wrapper);
    }

    @Override
    public void deleteRoleDeviceListByIds(List<Long> ids) {
        // 校验存在
        validateRoleDeviceExists(ids);
        // 删除
        roleDeviceMapper.deleteByIds(ids);
    }

    private void validateRoleDeviceExists(List<Long> ids) {
        List<RoleDeviceDO> list = roleDeviceMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(ROLE_DEVICE_NOT_EXISTS);
        }
    }

    private void validateRoleDeviceExists(Long id) {
        if (roleDeviceMapper.selectById(id) == null) {
            throw exception(ROLE_DEVICE_NOT_EXISTS);
        }
    }

    @Override
    public RoleDeviceDO getRoleDevice(Long id) {
        return roleDeviceMapper.selectById(id);
    }

    @Override
    public PageResult<RoleDeviceDO> getRoleDevicePage(RoleDevicePageReqVO pageReqVO) {
        return roleDeviceMapper.selectPage(pageReqVO);
    }

}